package bocchi.card;

import bocchi.BocchiCore;
import bocchi.base.BaseCustomCard;
import bocchi.base.BaseCustomPower;
import bocchi.general.Util;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.cards.CardGroup;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import com.megacrit.cardcrawl.powers.AbstractPower;

import java.util.ArrayDeque;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;

public class NeverForget extends BaseCustomCard {
    public static final String RAW_ID = NeverForget.class.getSimpleName();
    public static final String GAME_ID = BocchiCore.getGameID(RAW_ID);

    public NeverForget() {
        super(RAW_ID);
        exhaust = true;
    }

    @Override
    public void use(AbstractPlayer player, AbstractMonster monster) {
        BaseCustomPower power = new BaseCustomPower(RAW_ID, AbstractPower.PowerType.BUFF, player, 1) {
            private final Queue<AbstractCard> lastCards = new ArrayDeque<>();

            @Override
            public void onPlayCard(AbstractCard card, AbstractMonster m) {
                if (lastCards.contains(card)) return;
                lastCards.add(card);
                if (lastCards.size() > amount) lastCards.poll();
                updateDescription();
            }

            @Override
            public void atEndOfTurn(boolean isPlayer) {
                if (lastCards.isEmpty()) return;

                for (int i = 0; i < amount; i++) {
                    AbstractCard card = lastCards.poll();
                    if (card == null) continue;

                    CardGroup group = Util.findCard(card.uuid);
                    if (group == null) continue;

                    if (group == player.exhaustPile) {
                        player.hand.addToHand(card);
                        player.exhaustPile.removeCard(card);
                    } else {
                        group.moveToHand(card);
                    }

                    card.retain = true;
                }
                lastCards.clear();

                updateDescription();
            }

            @Override
            public void updateDescription() {
                if (lastCards == null || lastCards.isEmpty()) {
                    description = descriptions[1];
                    return;
                }

                List<String> cardsStrings = lastCards.stream().map(card -> card.name).collect(Collectors.toList());
                description = String.format(descriptions[0], String.join(", ", cardsStrings));
            }
        };

        Util.applyPower(player, player, power);
    }

    @Override
    public void upgrade() {
        super.upgrade();
        exhaust = false;
    }
}

